package twitpic.api
{
	import flash.display.*;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.utils.ByteArray;

	import twitpic.api.data.*;
	import twitpic.api.event.TwitpicEvent;

	public class Twitpic extends EventDispatcher
	{
		public function Twitpic()
		{
			super();
			//imageLoader = new Loader();
			//bmpData = null;
			loaders = [];
			boundary = '---------------------------7d76d1b56035e';
			//imageLoader.addEventListener(Event.COMPLETE, onImageLoadComplete);
			addLoader(UPLOAD, onUpload);
			addLoader(UPLOAD_POST, onUploadAndPost);
		}

		public function setAuthenticationCredentials(username:String, password:String):void {
			this.username = username;
			this.password = password;
		}

		public function uploadPost(imageBytes:ByteArray, msg:String):void {
			var header:String = '--' + boundary + '\r\n';
			var footer:String = '--' + boundary + '--';
			var username:String = "Content-Disposition:form-data; name=\"username\"\r\n\r\n" + username + "\r\n";
			var password:String = "Content-Disposition:form-data; name=\"password\"\r\n\r\n" + password + "\r\n";
			var media:String = "Content-Disposition:form-data; name=\"media\"; filename=\"image.jpg\"\r\n"
					+ "Content-Type: image/jpeg\r\n\r\n";
			if (msg!=null || msg!="") {
				var msgBytes:String = "Content-Disposition:form-data; name=\"message\"\r\n\r\n";
			}
			var sendBytes:ByteArray = new ByteArray();
			var plainBytes1:ByteArray = new ByteArray();
			var plainBytes2:ByteArray = new ByteArray();
			var plainBytes3:ByteArray = new ByteArray();
			var plainBytes4:ByteArray = new ByteArray();



			plainBytes1.writeMultiByte(header+username+header+password+header+msgBytes, "ascii");
			plainBytes2.writeUTFBytes(msg);
			plainBytes4.writeMultiByte("\r\n"+header+media, "ascii");
			plainBytes3.writeMultiByte("\r\n--"+boundary+"\r\n", "ascii");
			//plainBytes2.writeMultiByte(header+msgBytes, "ascii");

			sendBytes.writeBytes(plainBytes1, 0, plainBytes1.length);
			sendBytes.writeBytes(plainBytes2, 0, plainBytes2.length);
			sendBytes.writeBytes(plainBytes4, 0, plainBytes4.length);
			sendBytes.writeBytes(imageBytes, 0, imageBytes.length);
			//sendBytes.writeBytes(plainBytes2, 0, plainBytes2.length);
			sendBytes.writeBytes(plainBytes3, 0, plainBytes3.length);
			sendBytes.position = 0;
			postRequest(UPLOAD_POST, sendBytes);
		}

		public function upload(imageBytes:ByteArray):void {
			var header:String = '--' + boundary + '\r\n';
			var footer:String = '--' + boundary + '--';
			var username:String = "Content-Disposition:form-data; name=\"username\"\r\n\r\n" + username + "\r\n";
			var password:String = "Content-Disposition:form-data; name=\"password\"\r\n\r\n" + password + "\r\n";
			var media:String = "Content-Disposition:form-data; name=\"media\"; filename=\"image.jpg\"\r\n"
					+ "Content-Type: image/jpeg\r\n\r\n";
			var sendBytes:ByteArray = new ByteArray();
			var plainBytes1:ByteArray = new ByteArray();
			var plainBytes2:ByteArray = new ByteArray();


			plainBytes1.writeMultiByte(header+username+header+password+header+media, "ascii");
			plainBytes2.writeMultiByte("\r\n--"+boundary+"\r\n", "ascii");

			sendBytes.writeBytes(plainBytes1, 0, plainBytes1.length);
			sendBytes.writeBytes(imageBytes, 0, imageBytes.length);
			sendBytes.writeBytes(plainBytes2, 0, plainBytes2.length);
			sendBytes.position = 0;
			postRequest(UPLOAD, sendBytes);
		}

		private function onUpload(event:Event):void {
			var xml:XML = new XML(this.getLoader(UPLOAD).data);
			//var resArray:Array = new Array();
           // for each (var tempXML:XML in xml.children()) {
				var twitpicRes:TwitpicResponse = new TwitpicResponse (xml);
            //    resArray.push(twitpicRes);
            //}
			var r:TwitpicEvent = new TwitpicEvent(TwitpicEvent.ON_UPLOAD);
			//r.data = resArray;
			r.data = twitpicRes;
			dispatchEvent(r);
		}

		private function onUploadAndPost(event:Event):void {
			var xml:XML = new XML(this.getLoader(UPLOAD_POST).data);
			var twitpicRes:TwitpicResponse = new TwitpicResponse(xml);
			var r:TwitpicEvent = new TwitpicEvent(TwitpicEvent.ON_UPLOAD_POST);
			r.data = twitpicRes;
			dispatchEvent(r);
		}

		private function postRequest(api:String, byteData:ByteArray):void {
			var request:URLRequest = null;
			if (api==UPLOAD) {
				request = new URLRequest(UPLOAD_URL);
			} else if (api==UPLOAD_POST) {
				request = new URLRequest(UPLOAD_POST_URL);
			}

			request.data = byteData;
			request.method = URLRequestMethod.POST;
			request.contentType = "multipart/form-data; boundary=" + boundary;

			var loader:URLLoader = getLoader(api);
			loader.load(request);

		}

		private function addLoader(name:String, completeHandler:Function):void
		{
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, completeHandler);
			//loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			//loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
			this.loaders[name] = loader;
		}

		private function getLoader(name:String):URLLoader
		{
			return this.loaders[name] as URLLoader;
		}

		private static const UPLOAD_POST:String = "onTwitpicUploadPost";
		private static const UPLOAD:String = "onTwitpicUpload";

		private static const UPLOAD_POST_URL:String =
			"http://twitpic.com/api/uploadAndPost";
		private static const UPLOAD_URL:String =
			"http://twitpic.com/api/upload";

		private var username:String = null;
		private var password:String = null;
		//private var imageLoader:Loader = null;
		//private var bmpData:BitmapData = null;
		//private var imageBytes:ByteArray = null;

		private var loaders:Array;
		private var useHttps:Boolean;
		var boundary:String = null;
	}
}